<template>
  <div class="app-container sur-resource">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="categoryName"
              placeholder="请输入分类名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="categoryOptions"
              :props="{ label: 'categoryName', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="资源名称" prop="resourceName">
            <el-input
                v-model="queryParams.resourceName"
                placeholder="请输入资源名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="上映时间" prop="resourceDay">
            <el-input
                v-model="queryParams.resourceDay"
                placeholder="请输入上映时间"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="地区" prop="resourceAddress">
            <el-input
                v-model="queryParams.resourceAddress"
                placeholder="请输入地区"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="免费商用" prop="resourceFree">
            <el-select v-model="queryParams.resourceFree" clearable placeholder="请选择是否免费商用">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['sources:surResource:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['sources:surResource:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['sources:surResource:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['sources:surResource:export']"
            >导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Upload"
                @click="handleOpenUploadList"
            >上传记录
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="surResourceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="海报" align="center" prop="resourceImg">
            <template #default="scope">
              <image-preview :src="scope.row.resourceImg" width="50px" height="50px"/>
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" width="120px" prop="categoryName"/>
          <el-table-column label="资源名称" align="center" width="200px" prop="resourceName"/>
          <el-table-column label="资源状态" align="center" width="100px" prop="resourceStatus">
            <template #default="scope">
              <tc-status :status="scope.row.resourceStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="上映时间" align="center" width="180px" prop="resourceDay"/>
          <el-table-column label="评分" align="center" prop="resourceScore"/>
          <el-table-column label="地区" align="center" prop="resourceAddress"/>
          <el-table-column label="标签" align="center" width="180px" prop="resourceTags"/>
          <el-table-column label="免费商用" align="center" prop="resourceFree">
            <template #default="scope">
              {{ scope.row.resourceFree == 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="200px" class-name="small-padding fixed-width">
            <template #default="scope">
              <div style="display: flex">
                <el-upload
                    :action="uploadImgUrl"
                    :headers="headers"
                    :data="{ resourceId: scope.row.id }"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :on-progress="(evt, file) => handleUploadProgress(evt, file, scope.row)"
                    :before-upload="file => handleBeforeUpload(file, scope.row)"
                    :limit="100"
                    style="margin: 0 12px"
                >
                  <el-button
                      type="text"
                      icon="Upload"
                  >上传
                  </el-button>
                </el-upload>
                <el-button
                    type="text"
                    icon="Edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['sources:surResource:edit']"
                >修改
                </el-button>
                <el-button
                    type="text"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['sources:surResource:remove']"
                >删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改资源管理对话框 -->
    <el-drawer :title="title" v-model="open" size="70%" :close-on-click-modal="false" append-to-body>
      <div>
        <el-form ref="surResourceRef" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属分类" prop="categoryId">
                <el-tree-select
                    v-model="form.categoryId"
                    :data="categoryOptions"
                    :props="{label: 'categoryName', children: 'children'}"
                    value-key="id"
                    placeholder="请选择父分类"
                    check-strictly
                    @change="selectCategoryChange"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资源名称" prop="resourceName">
                <el-input v-model="form.resourceName" placeholder="请输入资源名称"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="资源描述" prop="resourceDesc">
                <editor v-if="open" v-model="form.resourceDesc" :height="200" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="上映时间" prop="resourceDay">
                <el-input v-model="form.resourceDay" placeholder="请输入上映时间"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评分" prop="resourceScore">
                <el-input v-model="form.resourceScore" placeholder="请输入评分"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地区" prop="resourceAddress">
                <el-input v-model="form.resourceAddress" placeholder="请输入地区"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="免费商用" prop="resourceFree">
                <el-switch v-model="form.resourceFree" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="标签" prop="resourceTags">
                <el-input v-model="form.resourceTags" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="缩略图" prop="resourceImg">
                <image-upload v-model="form.resourceImg" :file-size="200" :limit="1"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12"></el-col>
            <el-col :span="12"></el-col>
          </el-row>
        </el-form>
        <div v-if="updateFlag" style="padding: 20px;">
          <h4 style="font-size: 18px; font-weight: 600; color: #333333">资源列表</h4>
          <sur-resource-detail style="padding: 10px 0;" :resource-id="form.id" />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-drawer>

    <div v-if="openUploadList" class="upload-list-wrap">
      <div class="upload-list-title">
        <span>上传记录</span>
        <el-button text icon="Close" @click="handleCloseList"></el-button>
      </div>
      <div class="upload-list-upload">
        <ul>
          <li v-for="(item, index) in uploadList" :key="index">
            <div class="ulu-title tc-ellipsis">{{ item.name }}</div>
            <el-progress class="ulu-progress" :percentage="item.rate" :status="item.status" />
            <div class="ulu-rate">{{ item.netRate }}</div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup name="SurResource">
import {
  listSurResource,
  getSurResource,
  delSurResource,
  addSurResource,
  updateSurResource
} from "@/api/sources/surResource";
import {listSurResourceCategoryAll} from "@/api/sources/surResourceCategory.js";
import Editor from "@/components/Editor/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import TcStatus from "@/components/TcStatus/index.vue";
import SurResourceDetail from "@/views/sources/surResourceDetail/index.vue";
import {getToken} from "@/utils/auth.js";

const {proxy} = getCurrentInstance();

const surResourceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 上传相关
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/sources/surResourceDetail/upload");
const headers = ref({ Authorization: "Bearer " + getToken() });
const openUploadList = ref(false);
const uploadList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    categoryName: null,
    resourceType: null,
    resourceName: null,
    resourceImg: null,
    resourceDesc: null,
    resourceStatus: null,
    resourceDay: null,
    resourceScore: null,
    resourceAddress: null,
    resourceTags: null,
    resourceFree: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

// 标记更新
const updateFlag = ref(false);

// 分类名称
const categoryName = ref('');
const categoryOptions = ref([]);
const categoryList = ref([]);

/** 查询资源管理列表 */
function getList() {
  loading.value = true;
  listSurResource(queryParams.value).then(response => {
    surResourceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    categoryId: null,
    categoryName: null,
    resourceType: null,
    resourceName: null,
    resourceImg: null,
    resourceDesc: null,
    resourceStatus: 0,
    resourceDay: null,
    resourceScore: null,
    resourceAddress: null,
    resourceTags: null,
    resourceFree: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("surResourceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
  getTreeList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资源";
  updateFlag.value = false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSurResource(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资源";
    updateFlag.value = true;
  });
}

/** 关闭文件上传列表 */
function handleCloseList() {
  openUploadList.value = false;
}

function handleOpenUploadList() {
  openUploadList.value = true;
}

function handleUploadSuccess(res, file) {
  console.log('success')
  if (uploadList.value && uploadList.value.length > 0) {
    const index = uploadList.value.findIndex(x => x.uid === file.uid);
    if (index >= 0) {
      const fileItem = uploadList.value[index];
      fileItem.netRate = "上传成功";
      fileItem.status = "success";
      uploadList.value = [...uploadList.value];
    }
  }
}

function handleUploadError(error, file) {
  if (uploadList.value && uploadList.value.length > 0) {
    const index = uploadList.value.findIndex(x => x.uid === file.uid);
    if (index >= 0) {
      const fileItem = uploadList.value[index];
      fileItem.netRate = "上传异常";
      fileItem.status = "exception";
    }
  }
}

function handleUploadProgress(evt, file, row) {
  if (uploadList.value && uploadList.value.length > 0) {
    const index = uploadList.value.findIndex(x => x.uid === file.uid);
    if (index >= 0) {
      const fileItem = uploadList.value[index];
      fileItem.rate = parseInt(evt.percent);
      if (fileItem.loaded && fileItem.timeStamp) {
        let loadedSub = evt.loaded - fileItem.loaded;
        let timeStampSub = evt.timeStamp - fileItem.timeStamp;
        let seconds = Number(timeStampSub / 1000).toFixed(8);
        let calcRate = Number(loadedSub / 8 / seconds).toFixed(8);
        if (evt.total === evt.loaded) {
          fileItem.netRate = "保存中..."
        } else {
          fileItem.netRate = handleNatRate(calcRate);
        }
      }
      fileItem.loaded = evt.loaded;
      fileItem.timeStamp = evt.timeStamp;
    }
  }
}

function handleBeforeUpload(file, row) {
  uploadList.value.push({
    name: file.name,
    uid: file.uid,
    rate: 0,
    status: '',
    resourceId: row.id
  });
  openUploadList.value = true;
  return true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["surResourceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSurResource(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSurResource(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资源管理编号为"' + _ids + '"的数据项？').then(function () {
    return delSurResource(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sources/surResource/export', {
    ...queryParams.value
  }, `surResource_${new Date().getTime()}.xlsx`)
}

function getTreeList() {
  listSurResourceCategoryAll({}).then(res => {
    if (res.code === 200) {
      categoryList.value = res.data;
      // 初始化数结构数据
      const menu = { id: '0', categoryName: "主分类", children: [] };
      menu.children = proxy.handleTree(res.data, "id", "pid");
      categoryOptions.value = [menu];
    }
  });
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.categoryId = data.id;
  handleQuery();
};

/** 分类变化 */
function selectCategoryChange(target) {
  if (target) {
    const matArr = categoryList.value.filter(x => x.id === target);
    if (matArr && matArr.length > 0) {
      form.value.categoryName = matArr[0].categoryName;
    } else {
      form.value.categoryName = "";
    }
  } else {
    form.value.categoryName = "";
  }
}

function handleNatRate(rate) {
  if (!rate) {
    return '';
  }
  let unitArr = ['B/S', 'KB/S', 'MB/S', 'GB/S'];
  let nRate = rate;
  let count = 0;
  while(nRate > 1024) {
    nRate = Number(nRate / 1024).toFixed(6);
    count++;
  }
  let realRate = Number(nRate).toFixed(2);
  return realRate + unitArr[count];
}


getList();
getTreeList();
</script>

<style lang="scss" scoped>
.sur-resource {

  .upload-list-wrap {
    position: fixed;
    right: 0;
    bottom: 0;
    width: 500px;
    height: 400px;
    background-color: #ffffff;
    z-index: 100;
    box-shadow: -2px -2px 6px 2px rgba(0, 0, 0, 0.2);
    padding: 10px;

    .upload-list-title {
      color: #333333;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .upload-list-upload {
      height: 350px;
      overflow: auto;

      > ul {

        > li {
          display: flex;
          align-items: center;
          height: 40px;
          background-color: #f5f5f5;
          padding-left: 8px;
          margin-bottom: 6px;
          border-radius: 8px;

          .ulu-title {
            max-width: 160px;
          }

          .ulu-progress {
            margin-left: 10px;
            width: 240px;
          }
        }
      }
    }

  }
}
</style>
